using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement.Return;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement.Return
{
    /// <summary>
    /// 获取退货通知单明细列表查询处理器
    /// </summary>
    public class GetReturnNoticeDetailListHandler : IRequestHandler<GetReturnNoticeDetailListCommand, APIResult<GetReturnNoticeDetailListDto>>
    {
        private readonly RBACDbContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        public GetReturnNoticeDetailListHandler(RBACDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 处理获取退货通知单明细列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>退货通知单明细列表结果</returns>
        public async Task<APIResult<GetReturnNoticeDetailListDto>> Handle(GetReturnNoticeDetailListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建基础查询 - 直接从退货物料表查询，关联退货通知单
                var query = _dbContext.Set<ReturnMaterials>()
                    .Where(rm => !rm.IsDeleted)
                    .Join(_dbContext.Set<ReturnNotice>()
                            .Where(rn => !rn.IsDeleted),
                        rm => rm.ReturnNoticeId,
                        rn => rn.Id,
                        (rm, rn) => new { Material = rm, Notice = rn })
                    .AsQueryable();

                // 应用搜索条件
                if (!string.IsNullOrWhiteSpace(request.BillCode))
                {
                    query = query.Where(x => x.Notice.BillCode != null && x.Notice.BillCode.Contains(request.BillCode));
                }

                if (!string.IsNullOrWhiteSpace(request.CustomerName))
                {
                    query = query.Where(x => x.Notice.CustomerName != null && x.Notice.CustomerName.Contains(request.CustomerName));
                }

                if (!string.IsNullOrWhiteSpace(request.MaterialName))
                {
                    query = query.Where(x => x.Material.MaterialName != null && x.Material.MaterialName.Contains(request.MaterialName));
                }

                if (!string.IsNullOrWhiteSpace(request.MaterialCode))
                {
                    query = query.Where(x => x.Material.MaterialCode != null && x.Material.MaterialCode.Contains(request.MaterialCode));
                }

                if (!string.IsNullOrWhiteSpace(request.SalesOrderNumber))
                {
                    query = query.Where(x => x.Material.SalesOrderNumber != null && x.Material.SalesOrderNumber.Contains(request.SalesOrderNumber));
                }

                if (request.StartDate.HasValue)
                {
                    query = query.Where(x => x.Notice.BillDate >= request.StartDate.Value);
                }

                if (request.EndDate.HasValue)
                {
                    query = query.Where(x => x.Notice.BillDate <= request.EndDate.Value.Date.AddDays(1).AddTicks(-1));
                }

                // 获取总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 分页查询
                var returnNoticeDetails = await query
                    .OrderByDescending(x => x.Notice.CreateTime)
                    .ThenBy(x => x.Material.SalesOrderNumber)
                    .ThenBy(x => x.Material.MaterialCode)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .Select(x => new ReturnNoticeDetailDto
                    {
                        Id = x.Material.Id,
                        BillCode = x.Notice.BillCode,
                        CustomerName = x.Notice.CustomerName,
                        BillDate = x.Notice.BillDate,
                        BillStatus = x.Notice.BillStatus,
                        BusinessStatus = x.Notice.BusinessStatus,
                        SalesOrderNumber = x.Material.SalesOrderNumber,
                        MaterialCode = x.Material.MaterialCode,
                        MaterialName = x.Material.MaterialName,
                        Specification = x.Material.Specification,
                        Unit = x.Material.Unit,
                        ReturnQuantity = x.Material.Quantity,
                        StockInQuantity = x.Material.StockInQuantity,
                        BatchNumber = x.Material.BatchNumber,
                        ReturnReason = x.Notice.ReturnReason,
                        ProcessingMethod = x.Notice.ProcessingMethod,
                        Warehouse = x.Notice.Warehouse,
                        Operator = x.Notice.Operator,
                        Reviewer = x.Notice.Reviewer,
                        ReviewDate = x.Notice.ReviewDate,
                        CreateTime = x.Material.CreateTime
                    })
                    .ToListAsync(cancellationToken);

                var result = new GetReturnNoticeDetailListDto
                {
                    PageDatas = returnNoticeDetails,
                    TotalCount = totalCount
                };

                return new APIResult<GetReturnNoticeDetailListDto>
                {
                    Code = APIEnums.Success,
                    Msg = "获取退货通知单明细列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new APIResult<GetReturnNoticeDetailListDto>
                {
                    Code = APIEnums.Fail,
                    Msg = "获取退货通知单明细列表失败：" + ex.Message,
                    Data = new GetReturnNoticeDetailListDto()
                };
            }
        }
    }
}